<script setup lang="ts">
import {insert} from "@/api/permission/role"
import {query} from "@/api/permission/permission"
//定义事件
import {onMounted, ref} from "vue";
import {ElMessage} from "element-plus";

const emit = defineEmits(["close", "refresh"]);
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  }
})
//默认选中的key
const selkeys = ref([1, 5]);
const treeRef = ref();
const form = ref({
  name: "",
  note: "",
  status: 1,
  menu:[]
})
async function add(){
  //获取全选 中的菜单
  let all = treeRef.value.getCheckedKeys();
  //获取半选的
  let half = treeRef.value.getHalfCheckedKeys();
  let menu = [];
  all.forEach(id => {
    let tmp = {};
    tmp.menuId = id;
    tmp.isHaft = 0; //全选
    menu.push(tmp);
  });
  half.forEach(id => {
    let tmp = {};
    tmp.menuId = id;
    tmp.isHaft = 1; //全选
    menu.push(tmp);
  });
  form.value.menu = menu;
  let rs = await insert(form.value)
  if(rs.code == 200){
    ElMessage({
      message: "新增成功",
      type: "success"
    })
    form.value = {}
    treeRef.value.setCheckedKeys([]);
    emit("refresh")
    emit("close")
  }
}
const data = ref([])
const defaultProps = {
  children:'children',
  label:'menuName'
}
//查询菜单树
async function queryTree(){
  let rs = await query({})
  if(rs.code == 200){
    data.value = rs.data
  }
}
function cls() {
  emit("close");
}
onMounted(()=>{
  queryTree();
})
</script>

<template>
<div>
    <el-dialog
      :model-value="visible"
      title="新增角色"
      width="500"
      @close="cls"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="form.note" />
        </el-form-item>
        <el-form-item label="授权">
          <el-tree
            class="tree"
            :data="data"
            node-key="id"
            ref="treeRef"
            :props="defaultProps"
            show-checkbox
            default-expand-all
            />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
      <el-button type="primary" @click="add">保存</el-button>
      <el-button @click="cls">取消</el-button>
        </div>
      </template>
    </el-dialog>
</div>
</template>

<style scoped lang="scss">
.tree{
  width: 100%;
  height: 300px;
  overflow-y: scroll;
  border: 1px solid #ccc;
}
</style>
